package com.hundsun.network.uc.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hundsun.network.uc.vo.Msg4Ws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张颖辉
 * @version 1.0
 * @Title:WebsocketEndPoint 消息处理根类
 * @Description:Comment for created type
 * @date 2018年3月5日下午2:31:48
 */

public class WebsocketHandler extends TextWebSocketHandler {
    private static Logger logger = LoggerFactory.getLogger(WebsocketHandler.class);
    // 保存所有的用户session
    private static Map<String, WebSocketSession> SESSION_MAP = new HashMap<String, WebSocketSession>();

    // 处理信息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //super.handleTextMessage(session, message);
        String msgStr = message.getPayload();
        logger.info("收到消息：" + message);
        logger.info("收到消息内容：" + msgStr);
        String resultMsg = msgStr + " received at server";
        logger.info("返回信息：" + resultMsg);
        TextMessage returnMessage = new TextMessage(resultMsg);
        session.sendMessage(returnMessage);
    }

    // 连接 就绪时
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        logger.debug("[{} : {}] has be connected...", session.getUri(), session.getId());
        SESSION_MAP.put(session.getId(), session);
        logger.info("返回id");
        Msg4Ws<String> msg4Ws = new Msg4Ws<String>(10000, "websokect sessionId", session.getId());
        String message = new ObjectMapper().writeValueAsString(msg4Ws); // 转为json
        TextMessage returnMessage = new TextMessage(message);
        session.sendMessage(returnMessage);
    }

    // 关闭 连接时
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        logger.debug("[{} : {}] has bean closed ...", session.getUri(), session.getId());
        SESSION_MAP.remove(session.getId());
    }

    // 处理传输时异常
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        // TODO Auto-generated method stub
        super.handleTransportError(session, exception);
    }

    // 支持局部消息
    @Override
    public boolean supportsPartialMessages() {
        // TODO Auto-generated method stub
        return super.supportsPartialMessages();
    }

    /**
     * @param message
     * @throws Exception
     * @Title:向所有用户推送消息
     * @Description:Comment for non-overriding methods
     * @author 张颖辉
     * @date 2018年3月5日下午3:47:50
     */
    public void sendMsgToAllUsers(WebSocketMessage<?> message) throws Exception {
        for (WebSocketSession user : SESSION_MAP.values()) {
            user.sendMessage(message);
        }
    }

    /**
     * @param wsSessionId
     * @param message
     * @throws IOException
     * @Title:向一个用户推送消息
     * @Description:Comment for non-overriding methods
     * @author 张颖辉
     * @date 2018年3月5日下午3:47:32
     */
    public void sendMsgToUser(String wsSessionId, WebSocketMessage<?> message) throws IOException {
        WebSocketSession session = SESSION_MAP.get(wsSessionId);
        if (session == null) {
            throw new RuntimeException("对应sessionid(" + wsSessionId + ")的session不存在");
        }
        session.sendMessage(message);
    }
}
